package com.daylive.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.daylive.model.Admin;
import com.daylive.model.Agent;
import com.daylive.page.Page;
import com.daylive.service.AgentService;
import com.daylive.service.Const;
import com.daylive.service.AdminService;
import com.daylive.util.DesTool;
import com.daylive.util.StringUtil;

@Controller
@RequestMapping("admin")
public class AdminController {
	private final Logger logger = Logger.getLogger(AdminController.class);
	
	@Autowired
	private AdminService adminService;
	@Autowired
	private AgentService  agentService;
	private List<Agent>  agentList = null;
	@Autowired
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	private void saveSession(Admin admin) {
		HttpSession session = getSession();
		session.setAttribute(Const.SESSION_ADMIN_ACCOUNT, admin.getAccount());
	}
	private void clearSession() {
		getSession().invalidate();
	}
	@RequestMapping("/main.do")
    public ModelAndView mainPage() {  
		logger.info("执行mainPage方法");
		ModelAndView mv = new ModelAndView("main");
		return mv;
	}

	@RequestMapping("/logout.do")
	public String logout() {
		clearSession();
		return "login";
	}

	@RequestMapping("/login.do")
	@ResponseBody
    public Object userLogin(@RequestParam String KEYDATA) {
		logger.info("执行userLogin方法");
		String errInfo = "";
		JSONObject json = new JSONObject();
		HttpSession session = getSession();
		String sessionCode = (String)session.getAttribute(Const.SESSION_CODE);//获取session中的验证码
		String KEY[] = KEYDATA.split(",zt,");
		System.out.println(KEY[0]+"888");
		Admin admin = adminService.getAdminByAccount(KEY[0]);
		String code = KEY[2];
		if(null == code || "".equals(code)){
			errInfo = "nullcode"; //验证码为空
		}else{
			if (sessionCode.equalsIgnoreCase(code)) {
				if(admin != null && DesTool.decode(admin.getPwd()).equals(KEY[1])) {
					saveSession(admin);
					errInfo = "success";
				}else {
					errInfo = "usererror";		
					}
					}else {
				errInfo = "codeerror";				 	//验证码输入有误
			}
		}
		json.put("result", errInfo);
		return json;
	}
	
	@RequestMapping("/index.do")
    public ModelAndView indexPage() {
		logger.info("执行indexPage方法");
		ModelAndView mv = new ModelAndView();
		HttpSession session = getSession();
		try {
			Admin admin = adminService.getAdminByAccount(String.valueOf(session.getAttribute(Const.SESSION_ADMIN_ACCOUNT)));
			if (admin.getStatus()==1) {
				mv.setViewName("index");
			}else{
				mv.addObject("msg", "此账号不可用");
				mv.setViewName("error");
			}
		} catch (Exception e) {
			ModelAndView mv1 = new ModelAndView("error");
			mv1.addObject("msg", "查询数据库出错！");
		}
		return mv;
	}
	@RequestMapping("/myPersonal.do")
    public  ModelAndView  my() {  
		HttpSession session = getSession();
		ModelAndView mv = new ModelAndView();
		try {
		Admin admin = adminService.getAdminByAccount(String.valueOf(session.getAttribute(Const.SESSION_ADMIN_ACCOUNT)));
		mv.addObject("admin", admin);
		mv.setViewName("personal_data");
		} catch (Exception e) {
			ModelAndView mv1 = new ModelAndView("error");
			mv1.addObject("msg", "查询数据库出错！");
		}
		return mv;
	}
	/**
		 * check_admin
		 * @return
		 */
		@RequestMapping("/admin_check.do")
		@ResponseBody
	    public String checkUser(@RequestParam String account) {  
			try {
				account = new String(account.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			Admin  admin= adminService.getAdminByAccount(account);
			
			return null== admin ? "0" : "1";
		}
	@RequestMapping("/admin_list.do")
	public ModelAndView getAdminList() {
		return getAdminList(null,1);
	}
	@RequestMapping("/admin_page_list.do")
	public ModelAndView getAdminList(@RequestParam("account") String account,@RequestParam int pageNumber) {
		Page<Admin> pageList = adminService.getAgentList(account, pageNumber);
		ModelAndView mv = new ModelAndView("admin_list");
		mv.addObject("currentPage", pageNumber);
		mv.addObject("account", account);
		mv.addObject("totalPage", pageList.getTotalPage());
		mv.addObject("totalCount", pageList.getTotalCount());
		mv.addObject("adminList", pageList.getResultList());
		return mv;
	}
	 @RequestMapping("/admin_add.do")
		public ModelAndView addAdmin() {
			ModelAndView mv = new ModelAndView();
			if(agentList == null || agentList.size() == 0) {
				this.agentList = agentService.getAgentList();
			}
			mv.setViewName("admin_add");
			mv.addObject("agentList",agentList);
			return mv;
		}
	   @RequestMapping("/admin_save.do")
	   	public ModelAndView saveAdmin(Admin admin) {
	   		ModelAndView mv = new ModelAndView();
	   		if(admin.getPwd()==null||admin.getPwd().equals("")){
	   			admin.setPwd(DesTool.encode("111111"));
	   		}else{
	   			admin.setPwd(DesTool.encode(admin.getPwd()));
	   		}
	   		admin.setAddTime(StringUtil.getStrDate());
	   		admin.setStatus(1);
	   		int rel = adminService.addAdmin(admin);
	   		mv.setViewName("success");
			mv.addObject("msg",rel > 0 ? "数据添加成功！" : "数据添加失败！");
			return mv;   		
	   	}
	   @RequestMapping("/admin_edit.do")
		public ModelAndView editAgent(@RequestParam("account")String  account) {
		  Admin admin = adminService.getAdminByAccount(account);
			ModelAndView mv = new ModelAndView();
			if(agentList == null || agentList.size() == 0) {
				this.agentList = agentService.getAgentList();
			}
			mv.addObject("agentList", agentList);
			mv.addObject("admin", admin);
			mv.setViewName("admin_edit");
			return mv;
		}
	    @RequestMapping("/admin_update.do")
	   	public ModelAndView updateAgent(Admin admin) {
	   		ModelAndView mv = new ModelAndView();
	   		admin.setPwd(DesTool.encode(admin.getPwd()));
	   		int rel =adminService.updateAdmin(admin);
	   		mv.setViewName("success");
			mv.addObject("msg",rel > 0 ? "数据修改成功！" : "数据修改失败！");
			return mv;   		
	   	}
	   @RequestMapping("/admin_del.do")
	 		public String deleteAgent(@RequestParam("account")String  account) {
		   	try {
				account = new String(account.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		   	adminService.delAdmin(account);
	 			return "success";
	 		}
	   
	 		@RequestMapping("/admin_delAll.do")
	 		public String deleteAll(String ids) {
	 			String[] array_IDS = ids.split(",");
	 			adminService.delAll(array_IDS);
	 			return "success";
	 		}
}